import { IIndex } from '../emr_interface';
import { Injectable } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import {EntityManager} from 'typeorm';
import { RoleEntity } from '../entity/role.entity';
import { Tableobj } from '../entity/tableobj';
import { TestclobEntity } from '../entity/testclob.entity';
import { guid } from '../comm';

@Injectable()
export class Index implements IIndex{
  constructor(
    @InjectEntityManager()
    private readonly em: EntityManager,
  ) {

  }

  async getallroles():Promise<RoleEntity[]>
  {
    const res=await this.em.query("select * from t_role");
    return res;
  }

  async getalltext():Promise<any[]>{
    return await this.em.query("select * from t_text");
  }

  //查询所有的文书信息 文书名称
  async getalltextbyname(textname:string):Promise<any[]>{
    return await this.em.query("select * from t_text where textname like '%"+textname+"%' ");
  }

  /*
  自定义操作
  * */
  //单集合查询
  async GetData(sqlstr:string):Promise<any>{
     return await this.em.query(sqlstr);
  }

  //多集合查询
  async GetDatas(sqltables:Tableobj[]):Promise<any>
  {
    try {
      let datas = new Array<any>();
      for (let i = 0; i < sqltables.length; i++) {
        let data = await this.em.query(sqltables[i].sql);
        let res = {
          tablename: sqltables[i].tablename,
          data: data
        }
        datas.push(res);
      }
      return datas
    }
    catch (e) {
      throw e.message;
    }

  }

  //单SQL操作
  async ExecuteSql(exesql:string):Promise<boolean>{
     try{

       await this.em.query(exesql);
       return true;
     }
     catch (e) {
       throw e.message
     }
  }

  //多sql事务处理
  async ExecuteBatch(exesqls:string[]):Promise<boolean>{
    try{
      await this.em.transaction(async tempem=>{
        for(let i=0;i<exesqls.length;i++)
        {
          await tempem.query(exesqls[i]);
        }
      })
      return true;
    }
    catch (e) {
      throw e.message
    }
  }

  async TestClob(tid:number,content:string):Promise<boolean>{
     try {

       // let idvar = await this.em.getRepository(TestclobEntity).query("select count(id) as idindex from T_TEST_CLOB");
       // let id: number = Number(idvar[0].idindex);
       // id = id + 1;
       //let data=await this.em.query("select TID,CONTENT idindex from T_PATIENT_DOC_COLB where ");


      //对象形式插入
       // await this.em.getRepository(TestclobEntity).save(
       //   {
       //     ID:guid(),
       //     TID:tid,
       //     CONTENT:content
       //   }
       // )

       "SQL语句形式进行插入"
       await this.em.query("insert into T_TEST_CLOB(TID,ID,CONTENT)values(:tid,:id,:content)",
         ["123","123","123"])

       return true;
     }
     catch (e) {
       throw e.message;
     }
  }

  async SetTestCLobByTid(tid:number):Promise<boolean>{
    try {
      let id=guid();
      let data=await this.em.query("select TID,CONTENT from T_PATIENT_DOC_COLB where tid="+tid+"");
      await this.em.getRepository(TestclobEntity).save(
        {
          ID:id,
          TID:tid,
          CONTENT:data[0].CONTENT
        }
      )
      return true;
    }
    catch (e) {
      throw e.message;
    }
  }

  async TransferDocsByPatientId(patientid:number):Promise<boolean>
  {
    try {
     // let id=guid();
      let sql:string="select a.TID,a.CONTENT from T_PATIENT_DOC_COLB a "+
                     "inner join T_PATIENTS_DOC b on a.tid=b.tid "+
                     "where b.patient_id="+patientid+"";

      let datas=await this.em.query(sql);

      //事务处理 -对象方式
      // await this.em.transaction(async tempem=>{
      //   for(let i=0;i<datas.length;i++)
      //   {
      //     await this.em.getRepository(TestclobEntity).delete({TID:datas[i].TID});
      //     await this.em.getRepository(TestclobEntity).save(
      //       {
      //         ID:guid(),
      //         TID:datas[i].TID,
      //         CONTENT:datas[i].CONTENT
      //       }
      //     )
      //   }
      // })

      //事务处理SQL语句方式
      await this.em.transaction(async tempem=>{
        for(let i=0;i<datas.length;i++)
        {
          await this.em.query("delete from T_TEST_CLOB where TID=:tid",[datas[i].TID]);
          await this.em.query("insert into T_TEST_CLOB(ID,TID,CONTENT)values(:id,:tid,:content)",[
                guid(),
                datas[i].TID,
                datas[i].CONTENT
          ])
        }
      })

      return true;
    }
    catch (e) {
      throw e.message;
    }
  }


}